package com.xiaoqi.reggie.controller;
import com.xiaoqi.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author：xiaoqi
 * @creat 2022/9/19 18:00
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffix=filename.substring(filename.lastIndexOf('.'));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg
        File file1=new File(basePath);
        if (!file1.exists()){
            file1.mkdir();//如果该文件夹不存在，那就创建一个
        }
        file.transferTo(new File(basePath+fileName));
        return R.success(fileName);
    }
    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response)throws IOException{
        //创建一个输入流将文件读取进来
        FileInputStream fileInputStream=new FileInputStream(new File(basePath+name));
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        byte[]bytes=new byte[1024];
        int len=0;
        while ((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        //关闭资源
        outputStream.close();
        fileInputStream.close();
    }
}
